//
//  UCDrawToolsClass.m
//  SDK开发版本
//
//  Created by 朱国良 on 16/9/4.
//  Copyright © 2016年 北京国泰北斗科技有限公司. All rights reserved.
//


#import "UCDrawToolsClass.h"
#import "UCMapView.h"
#import <GoogleMaps/GoogleMaps.h>
#import <CoreText/CoreText.h>
#import <MapKit/MapKit.h>
#import "Public.h"

@interface UCDrawToolsClass()<GMSMapViewDelegate>

@property(nonatomic, strong) GMSMapView *mapView;
//绘制飞行区域的时候判断是否为编辑
@property(nonatomic,assign)BOOL isEdit;
//点击多边形的点的数组
@property(nonatomic,strong)NSMutableArray *tapMarkers;
//无人机飞行区域
@property(nonatomic,strong)GMSMutablePath *path;
//当显示两个点的时候显示线
@property(nonatomic,strong)GMSPolyline *polyline;
//路径对象
@property(nonatomic,strong)GMSPolygon *polygon;

//画圆状态
@property(nonatomic,assign)BOOL isCircle;
@property(nonatomic,strong)GMSCircle *circle;
//拖拽marker
@property(nonatomic,strong)GMSMarker *circleMarker;
//圆心marker
@property(nonatomic,strong)GMSMarker *circleCenterMarker;
@end

@implementation UCDrawToolsClass

- (instancetype)initWithMapView:(UCMapView *)mapView{
    self = [super init];
    if (self) {
        self = [[UCDrawToolsClass alloc] init];
        self.mapView = [mapView valueForKey:@"map"];
        self.mapView.delegate = self;
    }
    return self;
}

- (NSMutableArray *)tapMarkers{
    if (_tapMarkers == nil) {
        _tapMarkers = [[NSMutableArray alloc] init];
    }
    return _tapMarkers;
}
- (GMSMutablePath *)path{
    if (_path == nil) {
        _path = [GMSMutablePath path];
    }
    return _path;
}
- (GMSPolyline *)polyline{
    if (_polyline == nil) {
        _polyline = [GMSPolyline polylineWithPath:nil];
    }
    return _polyline;
}
- (GMSPolygon *)polygon{
    if (_polygon == nil) {
        _polygon = [GMSPolygon polygonWithPath:self.path];
        _polygon.geodesic = YES;
    }
    return _polygon;
}
//拖拽marker
- (GMSMarker *)circleMarker{
    if (_circleMarker == nil) {
        _circleMarker = [[GMSMarker alloc] init];
        _circleMarker.icon = [self generateClusterIconWithCount:0 withMarker:NO];
        _circleMarker.draggable = YES;
        _circleMarker.map = _mapView;
    }
    return _circleMarker;
}
//圆心marker
- (GMSMarker *)circleCenterMarker{
    if (_circleCenterMarker == nil) {
        _circleCenterMarker = [[GMSMarker alloc] init];
        _circleCenterMarker.icon = [self generateClusterIconWithCount:0 withMarker:YES];
        _circleCenterMarker.map = _mapView;
    }
    return _circleCenterMarker;
}
- (GMSCircle *)circle{
    if (_circle == nil) {
        _circle = [GMSCircle circleWithPosition:self.circleCenterMarker.position radius:0];
    }
    return _circle;
}

#pragma mark - 编辑坐标
- (void)editingCoordinte{
    self.isEdit = YES;
    
    if (self.isCircle) { //画圆状态
        self.circleMarker.icon = [self generateClusterIconWithCount:0 withMarker:NO];
        self.circleMarker.groundAnchor = CGPointMake(0.5, 0.5);
        self.circleMarker.map = self.mapView;
    }else{
        //多边形状态
        if (self.tapMarkers.count == 0) return ;
        for (GMSMarker *marker in self.tapMarkers) {
            marker.draggable = YES;
            marker.icon = [self generateClusterIconWithCount:0 withMarker:YES];
            marker.groundAnchor = CGPointMake(0.5, 0.5);
        }
    }
}
#pragma mark - 编辑坐标完成
- (void)commitEdittingCoordinte{
    self.isEdit = NO;
    
    if (self.isCircle) { //画圆状态
        self.circleMarker.icon = [self generateClusterIconWithCount:0 withMarker:NO];
        self.circleMarker.groundAnchor = CGPointMake(0.5, 1);
    }else{
        //多边形状态
        if (self.tapMarkers.count == 0) return ;
        for (int i = 1; i<=self.tapMarkers.count; i++) {
            GMSMarker *marker = self.tapMarkers[i-1];
            marker.draggable = NO;
            marker.groundAnchor = CGPointMake(0.5, 1);
            marker.icon = [self generateClusterIconWithCount:i withMarker:YES];
        }
    }
}
#pragma mark - 删除所有的点和区域
- (void)wipeAllCoordintes{
    if (self.isCircle) {
        self.circleMarker.map = nil;
        self.circleCenterMarker.map = nil;
        self.circle.map = nil;
        self.circle = nil;
        self.circleCenterMarker = nil;
        self.circleMarker = nil;
        self.isCircle = NO;
        self.isEdit = NO;
        if (self.delegate && [self.delegate respondsToSelector:@selector(drawCircleAtCoordinate: withRadius:)]) {
            [self.delegate drawCircleAtCoordinate:self.circleCenterMarker.position withRadius:0];
        }
    }
    if (self.tapMarkers.count == 0) return ;
    self.isEdit = NO;
    if (self.tapMarkers.count < 3) { //当数组的长度小于3的时候标示画了一根线
        self.polyline.map = nil;
    }
    for (GMSMarker *marker in self.tapMarkers) {
        marker.map = nil;
    }
    self.path = nil;
    self.polygon.map = nil;
    [self.tapMarkers removeAllObjects];
}

/**
 *  根据半径画圆
 *
 *  @param radius 半径
 */
- (void)circleWithRadius:(CLLocationDistance)radius{
    self.circle.radius = radius;
    if (radius > 0) {
        self.circle.map = self.mapView;
    }
    self.circle.fillColor = [UIColor colorWithRed:246/255.0 green:221/255.0 blue:8/255.0 alpha:0.32];
    self.circle.strokeColor = [UIColor colorWithRed:246/255.0 green:221/255.0 blue:8/255.0 alpha:1];
    self.circle.strokeWidth = 1;
    self.circle.zIndex = 5;
}

/**
 *  根据半径获取拖拽的点
 *
 *  @param radius 半径
 *
 *  @return 拖拽的点
 */
- (CLLocationCoordinate2D)getDragPositionWithRadius:(CLLocationDistance)radius{
    CLLocationCoordinate2D center;
    MKCoordinateRegion tempRegion = MKCoordinateRegionMakeWithDistance(self.circle.position, 0, radius);
    MKCoordinateSpan span = tempRegion.span;
    center.latitude = self.circle.position.latitude + span.latitudeDelta;
    center.longitude = self.circle.position.longitude + span.longitudeDelta;
    return center;
}
/**
 *  计算两个点之间的距离
 *
 *  @param coord1 点1
 *  @param coord2 点2
 *
 *  @return 距离
 */
- (CLLocationDistance)getDistanceMetresBetweenLocationCoordinates:(CLLocationCoordinate2D)coord1 withOtherCoordinate:(CLLocationCoordinate2D)coord2{
    @autoreleasepool {
        CLLocation* location1 = [[CLLocation alloc] initWithLatitude:coord1.latitude longitude:coord1.longitude];
        CLLocation* location2 = [[CLLocation alloc] initWithLatitude: coord2.latitude longitude: coord2.longitude];
        return [location1 distanceFromLocation:location2];
    }
}

#pragma mark - 根据coordinate在地图上添加路径
- (void)drawAreaWithCoordinates:(CLLocationCoordinate2D)coordinate{
    
    GMSMarker *marker = [GMSMarker markerWithPosition:coordinate];
    marker.appearAnimation = kGMSMarkerAnimationPop;
    marker.zIndex = 5;
    marker.draggable = self.isEdit ? YES : NO;
    [self.tapMarkers addObject:marker];
    marker.icon = [self generateClusterIconWithCount:(self.isEdit ? 0 : self.tapMarkers.count) withMarker:YES];
    marker.map = _mapView;
    
    [self.path addCoordinate:coordinate];
    
    if (self.tapMarkers.count < 3) {
        self.polyline.path = self.path;
        self.polyline.spans = @[[GMSStyleSpan spanWithColor:[UIColor colorWithRed:246/255.0 green:221/255.0 blue:8/255.0 alpha:1.0]]];
        self.polyline.zIndex = 5;
        self.polyline.map = _mapView;
    }else{
        self.polyline.map = nil;
        self.polyline = nil;
        self.polygon.path = self.path;
        self.polygon.fillColor = [UIColor colorWithRed:246/255.0 green:221/255.0 blue:8/255.0 alpha:0.12];
        self.polygon.strokeColor = [UIColor colorWithRed:246/255.0 green:221/255.0 blue:8/255.0 alpha:1.0];
        self.polygon.strokeWidth = 1;
        self.polygon.zIndex = 5;
        self.polygon.map = _mapView;
    }
}

#pragma mark - 默认画圆
- (void)drawCircleWithCenter:(CLLocationCoordinate2D)center withRadius:(CLLocationDistance)radius{
    self.isCircle = YES;
    self.circleCenterMarker.position = center;
    self.circleMarker.position = center;
    if (self.delegate && [self.delegate respondsToSelector:@selector(drawCircleAtCoordinate: withRadius:)]) {
        [self.delegate drawCircleAtCoordinate:self.circleCenterMarker.position withRadius:0];
    }
}

#pragma mark - 手动的修改index位置的点的坐标
- (void)changeRcetPositionWith:(CLLocationCoordinate2D)position withIdex:(NSInteger)index{
    
    if (self.tapMarkers.count > 0) {
        GMSMarker *marker1 = self.tapMarkers[index];
        marker1.map = nil;
        
        GMSMarker *marker = [GMSMarker markerWithPosition:position];;
        marker.appearAnimation = kGMSMarkerAnimationPop;
        marker.zIndex = 5;
        marker.draggable = self.isEdit ? YES : NO;
        marker.icon = [self generateClusterIconWithCount:(self.isEdit ? 0 : index+1) withMarker:YES];
        marker.map = _mapView;
        [self.tapMarkers setObject:marker atIndexedSubscript:index];
        
        [self.path replaceCoordinateAtIndex:index withCoordinate:position];
        
        self.polygon.path = self.path;
        if (self.delegate && [self.delegate respondsToSelector:@selector(drawRectTapCoordinate:withIndex:)]) {
            [self.delegate drawRectTapCoordinate:position withIndex:index+1];
        }
    }
}

#pragma mark - 手动添加半径
- (void)drawCircleWithRadius:(CLLocationDistance)radius{
    if (self.isEdit) { //如果是处于编辑状态
        [self commitEdittingCoordinte];
    }
    [self circleWithRadius:radius];
    self.circleMarker.position = [self getDragPositionWithRadius:radius];
    if (self.delegate && [self.delegate respondsToSelector:@selector(drawCircleAtCoordinate: withRadius:)]) {
        [self.delegate drawCircleAtCoordinate:self.circleCenterMarker.position withRadius:radius];
    }
}

#pragma mark - 手动添加圆心
- (void)drawCircleWithCenter:(CLLocationCoordinate2D)center{
    self.isCircle = YES;
    [self wipeAllCoordintes];
    self.circleCenterMarker.position = center;
    if (self.delegate && [self.delegate respondsToSelector:@selector(drawCircleAtCoordinate: withRadius:)]) {
        [self.delegate drawCircleAtCoordinate:self.circleCenterMarker.position withRadius:0];
    }
}

#pragma mark - GMSMapViewDelegate
#pragma mark - 拖拽Marker状态
- (void)mapView:(GMSMapView *)mapView didDragMarker:(GMSMarker *)marker{
    if (self.isCircle) { //画圆状态下
        CLLocationDistance radius = [self getDistanceMetresBetweenLocationCoordinates:self.circleCenterMarker.position withOtherCoordinate:marker.position];
        [self circleWithRadius:radius];
        if (self.delegate && [self.delegate respondsToSelector:@selector(drawCircleAtCoordinate: withRadius:)]) {
            [self.delegate drawCircleAtCoordinate:self.circleCenterMarker.position withRadius:radius];
        }
    }else{ //画多边形
        //标记点击哪一个marker
        NSInteger index = 0 ;
        for (int i = 1; i<=self.tapMarkers.count; i++) {
            GMSMarker *mk = self.tapMarkers[i-1];
            if (mk == marker) {
                index = i;
                [self.path replaceCoordinateAtIndex:i-1 withCoordinate:marker.position];
                if (self.tapMarkers.count < 3) { //当前地图上显示的还是一条线
                    self.polyline.path = self.path;
                    continue ;
                }else{
                    self.polygon.path = self.path;
                }
            }
        }
        if (self.delegate && [self.delegate respondsToSelector:@selector(drawRectTapCoordinate:withIndex:)]) {
            [self.delegate drawRectTapCoordinate:marker.position withIndex:index];
        }
    }
}

#pragma mark - GMSMapViewDelegate
#pragma mark - 点击地图
- (void)mapView:(GMSMapView *)mapView didTapAtCoordinate:(CLLocationCoordinate2D)coordinate{
    if (self.isCircle) { //在画圆状态下。点击别的区域，就重新确定圆的坐标
        [self wipeAllCoordintes];
    }
    if (self.delegate && [self.delegate respondsToSelector:@selector(tapMapViewAtCoordinate:)]) {
        [self.delegate tapMapViewAtCoordinate:coordinate];
    }
}

#pragma mark - 获取Image
- (UIImage*)generateClusterIconWithCount:(NSUInteger)count withMarker:(BOOL)bl{
    
    int diameter = 26;
    CGRect rect = CGRectMake(0, 0, diameter, diameter);
    UIGraphicsBeginImageContextWithOptions(rect.size, NO, 0);
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    
    @autoreleasepool {
        if (self.isEdit) {
            //边框圆
            CGContextSetRGBStrokeColor(ctx, 255/255.0, 255/255.0, 255/255.0, 1);
            CGContextSetRGBFillColor(ctx, 255/255.0, 255/255.0, 255/255.0, 0.32);
            CGContextSetLineWidth(ctx, 2);
            CGContextAddArc(ctx, 13, 13, 10, 0, 2*M_PI, 0);
            CGContextDrawPath(ctx, kCGPathFillStroke);
        }else{
            if (bl) {
                [[UIColor colorWithPatternImage:MYBUNDLE_IMAGE_PATH(@"landing_points")] setFill];
            }else{
                if (self.isEdit) {
                    CGContextSetRGBStrokeColor(ctx, 255/255.0, 255/255.0, 255/255.0, 1);
                    CGContextSetLineWidth(ctx, 1);
                    CGContextAddArc(ctx, 13, 13, 10, 0, 2*M_PI, 0);
                    CGContextDrawPath(ctx, kCGPathStroke);
                }else{
                    [[UIColor colorWithRed:255/255.0 green:255/255.0 blue:255/255.0 alpha:0.0] setFill];
                }
            }
            CGContextSetLineWidth(ctx, 0);
            CGRect circleRect = CGRectMake(0, 0, diameter, diameter);
            circleRect = CGRectInset(circleRect, 0, 0);
            CGContextFillEllipseInRect(ctx, circleRect);
            CGContextStrokeEllipseInRect(ctx, circleRect);
            
            if (count > 0) {
                CTFontRef myFont = CTFontCreateWithName( (CFStringRef)@"Helvetica-Bold", 11.0f, NULL);
                UIColor *fontColor;
                fontColor = [UIColor blackColor];
                NSDictionary *attributesDict = [NSDictionary dictionaryWithObjectsAndKeys:(__bridge id)myFont, (id)kCTFontAttributeName,fontColor, (id)kCTForegroundColorAttributeName, nil];
                
                // create a naked string
                NSString *string = [[NSString alloc] initWithFormat:@"%lu", (unsigned long)count];
                
                NSAttributedString *stringToDraw = [[NSAttributedString alloc] initWithString:string attributes:attributesDict];
                
                // flip the coordinate system
                CGContextSetTextMatrix(ctx, CGAffineTransformIdentity);
                CGContextTranslateCTM(ctx, 0, diameter);
                CGContextScaleCTM(ctx, 1.0, -1.0);
                
                CTFramesetterRef frameSetter = CTFramesetterCreateWithAttributedString((__bridge CFAttributedStringRef)(stringToDraw));
                CGSize suggestedSize = CTFramesetterSuggestFrameSizeWithConstraints(frameSetter,CFRangeMake(0, stringToDraw.length),NULL,                   CGSizeMake(diameter, diameter),NULL);
                float midWidth = diameter / 2;
                midWidth -= suggestedSize.width / 2;
                
                CTLineRef line = CTLineCreateWithAttributedString((__bridge CFAttributedStringRef)stringToDraw);
                CGContextSetTextPosition(ctx, midWidth, 11);
                CTLineDraw(line, ctx);
                
                CFRelease(myFont);
                CFRelease(line);
                CFRelease(frameSetter);
            }
        }
        UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        return image;
    }
}
@end
